package com.dh.lc.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.dh.lc.mo.Coder;
import com.dh.lc.mo.ContactInfo;
import com.google.appengine.api.datastore.Key;

public class CoderDAO {

	public Coder getCoder(Key id) {
		Coder coder = null;
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			coder = em.find(Coder.class, id);
			coder.getContactInfo();
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}

		return coder;
	}
	
	public Coder getCoderByEmail(String email) {
		Coder coder = null;
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			//Query query = em.createQuery("SELECT info FROM com.dh.lc.mo.ContactInfo info WHERE info.email=\"email\" ORDER BY info.email ascending");
			Query query = em.createQuery("SELECT coder FROM com.dh.lc.mo.Coder coder WHERE coder.contactInfo.email=\"%email%\" ORDER BY info.email ascending");
//			query.setParameter("email", email);
			coder = (Coder) query.getSingleResult();
			tx.commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace(System.out);
			
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}

		return coder;
	}

	public void addCoder(Coder coder) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(coder);
		} finally {
			em.close();
		}
	}

	
	public void updateCoder(Coder coder) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.merge(coder);
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("unchecked")
	public long getCoderAmount() {
		long amount = 0;

		EntityManager em = EMF.get().createEntityManager();
		try {
			Query query = em.createQuery("SELECT p FROM com.dh.lc.mo.Coder p");
			List results = query.getResultList();
			amount = results.size();
			System.out.println("coder amount: " + amount);
			if (results.iterator().hasNext()) {
				for (Object c : results) {
					System.out.println(((Coder) c).getId());
				}
			} else {
				System.out.println("... no results ...");
			}

		} finally {
			em.close();
		}

		return amount;
	}
}
